//
// Created by JYL on 2024-06-17.
//
#include "bsp_adc.h"
#include "adc.h"


/*ADC中断采集，需要定时器更新事件映射，但是映射通道被占用了，只能使用软件的方式读取*/

volatile float voltage_vrefint_proportion = 8.0586080586080586080586080586081e-4f;

static uint16_t adcx_get_chx_value(ADC_HandleTypeDef *ADCx, uint32_t ch)
{
    static ADC_ChannelConfTypeDef sConfig = {0};
    sConfig.Channel = ch;
    sConfig.Rank = 1;
    sConfig.SamplingTime = ADC_SAMPLETIME_239CYCLES_5;//ADC_SAMPLETIME_3CYCLES;

    if (HAL_ADC_ConfigChannel(ADCx, &sConfig) != HAL_OK)
    {
        Error_Handler();
    }
    HAL_ADC_Start(ADCx);
    HAL_ADC_PollForConversion(ADCx, 50);
    return (uint16_t)HAL_ADC_GetValue(ADCx);
}

void init_vrefint_reciprocal(void)
{
    uint8_t i = 0;
    uint32_t total_adc = 0;
    for(i = 0; i < 200; i++)    //如果采样设置比较低，采集值不准
    {
        total_adc += adcx_get_chx_value(&hadc1, ADC_CHANNEL_VREFINT);
    }
    voltage_vrefint_proportion = 200 * 1.2f / total_adc;
}
/*旋转电位器*/
float get_temprate(void)
{
    uint16_t adcx = 0;
    float temperate;
    adcx = adcx_get_chx_value(&hadc1, ADC_CHANNEL_TEMPSENSOR);
    temperate = (float)adcx * voltage_vrefint_proportion;
    temperate = (temperate - 0.76f) * 400.0f + 25.0f;
    return temperate;
}
/*旋转电位器*/
float get_resister_voltage(void)
{
    float voltage;
    uint16_t adcx = 0;
    adcx = adcx_get_chx_value(&hadc2, ADC_CHANNEL_10);
    voltage =  (float)adcx * voltage_vrefint_proportion;
    return voltage;
}
/*获取电量 电量, 单位 1, 1 = 1%*/
float get_battery_voltage(void)
{
    float voltage;
    uint16_t adcx = 0;
    adcx = adcx_get_chx_value(&hadc3, ADC_CHANNEL_11);
    float resister_coefficient=11;    //(1K+10K)/1K=11
    voltage =  (float)adcx * voltage_vrefint_proportion * resister_coefficient;
    return voltage;
}


